package com.example.simple_flow.sia5;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.annotation.Transformer;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.dsl.MessageChannels;
import org.springframework.integration.file.FileWritingMessageHandler;
import org.springframework.integration.file.dsl.Files;
import org.springframework.integration.file.support.FileExistsMode;
import org.springframework.integration.transformer.GenericTransformer;

import java.io.File;

@Configuration
public class FileWriterIntegrationConfig {


    @Bean
    @Transformer(inputChannel = "textInChannel",outputChannel = "fileWriterChannel") //转换器
    public GenericTransformer<String,String> upperCaseTransfoemer(){
        return text ->text.toUpperCase();
    }

    @Bean
    @ServiceActivator(inputChannel = "fileWriteChannel") //表示接受来自filterWriterChannel的消息，并调用方法
    public FileWritingMessageHandler fileWriter(){      //声明文件写入消息处理器
        FileWritingMessageHandler handler= new FileWritingMessageHandler(new File("/temp/sia5/files"));
        handler.setExpectReply(false);   //激活不要有答复通道
        handler.setFileExistsMode(FileExistsMode.APPEND);
        handler.setAppendNewLine(true);
        return handler;
    }

       // 用一个bean来定义整个流,适配器和转换器之间的通道可以在流定义时候通过channel来应用
    @Bean
    public IntegrationFlow fileWriteFlow(){
        return IntegrationFlows
                .from(MessageChannels.direct("textInChannel"))
                .<String,String>transform(text->text.toUpperCase())
//                .channel(MessageChannels.direct("fileWriteChannel"))
                .handle(Files
                .outboundAdapter(new File("/tmp/sia5/files"))
                .fileExistsMode(FileExistsMode.APPEND)
                .appendNewLine(true))
                .get();
    }

}
